package com.hefeng.wx.common;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teautil.Common;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.hefeng.common.redis.service.RedisService;
import com.hefeng.wx.domain.WxDeviceReport;
import com.hefeng.wx.domain.WxDeviceUser;
import com.hefeng.wx.domain.WxMsg;
import com.hefeng.wx.handler.DeviceReportRedisHandler;
import com.hefeng.wx.mapper.WxDeviceReportMapper;
import com.hefeng.wx.mapper.WxDeviceUserMapper;
import com.hefeng.wx.mapper.WxMsgMapper;
import com.hefeng.wx.service.WxDeviceReportService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import util.Sample;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@SuppressWarnings("ALL")
@Slf4j
@Component
public class MessageListener {
    @Autowired
    WxDeviceReportService wxDeviceReportService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private MsgTaskSend taskSend;
    @Autowired
    private WxMsgMapper wxMsgMapper;
    @Autowired
    DeviceReportRedisHandler deviceReportRedisHandler;
    @Autowired
    private WxDeviceUserMapper wxDeviceUserMapper;
    @Autowired
    private WxDeviceReportMapper wxDeviceReportMapper;


    //报警存储集合
    List<WxDeviceReport> list = new ArrayList<WxDeviceReport>();

    //报警消息接受中心
    @KafkaListener(topics = {"resident_collection_alarm_topic"}, groupId = "collection-group")
    public void listener(ConsumerRecord<String, String> record) {
        try {

            Optional<?> optional = Optional.ofNullable(record.value());
            //获取消息
            String message = record.value();
            JSONObject data = JSONObject.fromObject(message);
            String deviceCode = data.getString("deviceCode");
            String time = String.valueOf(new Date(Long.valueOf(data.getString("messageTime"))));
            Date date = DateUtil.parse(time);
            //DateTime newDate3 = DateUtil.offsetHour(date);
            String formatDateTime = DateUtil.formatDateTime(date);
            //UserDto userDto = StartLoadingParameter.userDtoMap.get(deviceCode);
            // UserDto userDto1= (UserDto) wxDeviceUserMapper.getUserBindingDevice(deviceCode);
            //if (EmptyUtils.isEmpty(userDto)) {
            //   return ;
            //}
            //获取缓存内的数据时间

            //判断消息是否重复


            WxDeviceReport wxDeviceReport = new WxDeviceReport();

            WxDeviceReport wxDeviceReports = wxDeviceReportMapper.selectByTime(deviceCode);
            if (ObjectUtil.isNotNull(wxDeviceReports)) {
                long betweenDay = DateUtil.between(date, wxDeviceReports.getReportTime(), DateUnit.MINUTE);
                if (betweenDay < 3) {
                    return;
                }
            }
            WxDeviceUser user = wxDeviceUserMapper.getUser(deviceCode);
            wxDeviceReport.setUserId(user.getUserId());
            wxDeviceReport.setReportId(IdWorker.getId());
            wxDeviceReport.setDeviceCode(deviceCode);
            wxDeviceReport.setReportTitle("燃气泄露报警");
            wxDeviceReport.setReportTime(new Date(Long.valueOf(data.getString("messageTime"))));
            wxDeviceReport.setReportContent("设备在" + formatDateTime + "发生燃气泄露！");
            wxDeviceReport.setReportValue(Double.parseDouble(data.getString("concentration")));
            wxDeviceReport.setReporType("1");
            wxDeviceReport.setIsMsg(0);
            wxDeviceReport.setCreatedTime(new Date());
//          设置缓存
//          deviceReportRedisHandler.setDeviceReportRedis(wxDeviceReport);
//          deviceReportRedisHandler.isRepeatReport(wxDeviceReport);
            wxDeviceReportService.save(wxDeviceReport);


            //发送短信
            Client client = null;
            try {
                // for (int i = 0; i < userDto.getPhone().size(); i++) {
                client = Sample.createClient("LTAI4G9NUVeKwrPQh9QwPyMh", "P1NuKkn65iCM9YjunAfhCpBIN062Xg");
                SendSmsRequest sendSmsRequest = new SendSmsRequest()
                        //.setPhoneNumbers(userDto.getPhone().get(i).toString())
                        .setPhoneNumbers(user.getPhone())
                        .setSignName("海南合丰运维科技有限公司")
                        .setTemplateCode("SMS_235814724")
                        .setTemplateParam("{\"time\":\"" + formatDateTime + "\",\"event\":\"" + "燃气泄漏" + "\"}");
                // 复制代码运行请自行打印 API 的返回值
                SendSmsResponse sendResp = client.sendSms(sendSmsRequest);
                String code = sendResp.body.code;
                if (!Common.equalString(code, "OK")) {
                    com.aliyun.teaconsole.Client.log("错误信息: " + sendResp.body.message + "");
                }
                WxMsg wxMsg = new WxMsg();
                wxMsg.setReportId(wxDeviceReport.getReportId());
                wxMsg.setTitle(wxDeviceReport.getReportTitle());
                wxMsg.setContent("尊敬的用户您好，您关注的设备，在" + formatDateTime + "出现燃气泄漏告警，请登录微信进入小程序查看。");
                //wxMsg.setPhone(user.getPhone());
                wxMsg.setCreationTime(new Date());
                wxMsgMapper.insert(wxMsg);

            } catch (Exception e) {
                e.printStackTrace();
            }
            redisService.setCacheObject(deviceCode, wxDeviceReport);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // wxResidenceService

    }

    @KafkaListener(topics = {"smoke-event_topic"}, groupId = "zhxf-socket-group")
    public void listenerSmoke(ConsumerRecord<String, String> record) {
        try {
            Optional<?> optional = Optional.ofNullable(record.value());
            //获取消息
            String message = record.value();
            JSONObject data = JSONObject.fromObject(message);
            String deviceCode = data.getString("deviceCode");
            String type = data.getString("type");
            String time = String.valueOf(new Date(Long.valueOf(data.getString("messageTime"))));
            Date date = DateUtil.parse(time);
            //DateTime newDate3 = DateUtil.offsetHour(date);
            String formatDateTime = DateUtil.formatDateTime(date);
            //UserDto userDto = StartLoadingParameter.userDtoMap.get(deviceCode);
            // UserDto userDto1= (UserDto) wxDeviceUserMapper.getUserBindingDevice(deviceCode);
            //if (EmptyUtils.isEmpty(userDto)) {
            //   return ;
            //}
            //获取缓存内的数据时间

            //判断消息是否重复

            WxDeviceReport wxDeviceReport = new WxDeviceReport();

            WxDeviceReport wxDeviceReports = wxDeviceReportMapper.selectByTime(deviceCode);
            if (ObjectUtil.isNotNull(wxDeviceReports)) {
                long betweenDay = DateUtil.between(date, wxDeviceReports.getReportTime(), DateUnit.MINUTE);
                if (betweenDay < 3) {
                    return;
                }
            }
            WxDeviceUser user = wxDeviceUserMapper.getUser(deviceCode);
            wxDeviceReport.setUserId(user.getUserId());
            wxDeviceReport.setReportId(IdWorker.getId());
            wxDeviceReport.setDeviceCode(deviceCode);
            wxDeviceReport.setReportTitle(type);
            wxDeviceReport.setReportTime(new Date(Long.valueOf(data.getString("messageTime"))));
            wxDeviceReport.setReportContent("设备在" + formatDateTime + "发生" + type);
            wxDeviceReport.setReportValue(Double.parseDouble(data.getString("concentration")));
            wxDeviceReport.setReporType("1");
            wxDeviceReport.setIsMsg(0);
            wxDeviceReport.setCreatedTime(new Date());
//          设置缓存
//          deviceReportRedisHandler.setDeviceReportRedis(wxDeviceReport);
//          deviceReportRedisHandler.isRepeatReport(wxDeviceReport);
            wxDeviceReportService.save(wxDeviceReport);


            //发送短信
            Client client = null;
            try {
                // for (int i = 0; i < userDto.getPhone().size(); i++) {
                client = Sample.createClient("LTAI4G9NUVeKwrPQh9QwPyMh", "P1NuKkn65iCM9YjunAfhCpBIN062Xg");
                SendSmsRequest sendSmsRequest = new SendSmsRequest()
                        //.setPhoneNumbers(userDto.getPhone().get(i).toString())
                        .setPhoneNumbers(user.getPhone())
                        .setSignName("海南合丰运维科技有限公司")
                        .setTemplateCode("SMS_235814724")
                        .setTemplateParam("{\"time\":\"" + formatDateTime + "\",\"event\":\"" + type + "\"}");
                // 复制代码运行请自行打印 API 的返回值
                SendSmsResponse sendResp = client.sendSms(sendSmsRequest);
                String code = sendResp.body.code;
                if (!Common.equalString(code, "OK")) {
                    com.aliyun.teaconsole.Client.log("错误信息: " + sendResp.body.message + "");
                }
                WxMsg wxMsg = new WxMsg();
                wxMsg.setReportId(wxDeviceReport.getReportId());
                wxMsg.setTitle(wxDeviceReport.getReportTitle());
                wxMsg.setContent("尊敬的用户您好，您关注的设备，在" + formatDateTime + "出现" + type + "，请登录微信进入小程序查看。");
                //wxMsg.setPhone(user.getPhone());
                wxMsg.setCreationTime(new Date());
                wxMsgMapper.insert(wxMsg);

            } catch (Exception e) {
                e.printStackTrace();
            }
            redisService.setCacheObject(deviceCode, wxDeviceReport);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
